/*
 * Copyright (C) 2012  Romain DUBOIS
 * 
 * This file is part of NeMoS - Network and Modular Software
 * 
 * NeMoS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NeMoS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NeMoS.  If not, see <http://www.gnu.org/licenses/>.
 */
package nemos.resources.impl.internal;

import java.util.IllegalFormatException;
import java.util.Locale;
import java.util.MissingResourceException;

import nemos.resources.IResources;
import nemos.resources.IResourcesManager;
import nemos.resources.UnsupportedResourceType;
import nemos.util.i18n.BundleLocalization;
import nemos.util.i18n.ITranslator;
import nemos.util.log.NemosLogger;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.osgi.framework.Bundle;
import org.osgi.service.component.ComponentContext;

/**
 * TranslatorImpl : The translator standard implementation.
 * 
 * <p>
 * This implementation looks for localized messages through the
 * {@link IResourcesManager} service first. Then, it looks in the bundle
 * localization file for translation.
 * </p>
 * 
 * @author Romain DUBOIS
 */
@Service(value = ITranslator.class, serviceFactory = true)
@Component
public class TranslatorImpl implements ITranslator {

    /** The unsupported type key */
    private static final String INVALID_TYPE_KEY = "RESOURCE_TYPE_NOT_SUPPORTED"; //$NON-NLS-1$
    /** The invalid format code */
    private static final String INVALID_FORMAT_KEY = "INVALID_FORMAT"; //$NON-NLS-1$
    /** The missing key code */
    private static final String MISSING_KEY = "MISSING_KEY"; //$NON-NLS-1$

    /** The component context */
    private ComponentContext mContext;
    /** The bundle locale translator */
    private BundleLocalization mLocalization;
    /** The logger */
    private NemosLogger mLogger;

    /** The resources manager */
    @Reference(name = "resources")
    private IResourcesManager mResourcesManager;

    /**
     * Constructor
     */
    public TranslatorImpl() {
        super();
    }

    /**
     * The component activation method.
     * 
     * @param pContext
     *            The component context
     */
    @Activate
    public void start(final ComponentContext pContext) {
        mContext = pContext;
        mLocalization = new BundleLocalization(mContext.getUsingBundle());
        mLogger = new NemosLogger(mContext.getBundleContext(), getClass(), new BundleLocalization(
                getClass()));
    }

    /**
     * {@inheritDoc}
     * 
     * @see nemos.util.i18n.ITranslator#getLabel(java.lang.String,
     *      java.lang.Object[])
     */
    @Override
    public String getLabel(final String pKey, final Object... pParams) {
        return translateText(null, pKey, null, pParams);
    }

    /**
     * {@inheritDoc}
     * 
     * @see nemos.util.i18n.ITranslator#getText(java.lang.String,
     *      java.lang.String, java.lang.Object[])
     */
    @Override
    public String getText(final String pBaseName, final String pKey, final Object... pParams) {
        return translateText(pBaseName, pKey, null, pParams);
    }

    /**
     * {@inheritDoc}
     * 
     * @see nemos.util.i18n.ITranslator#translateLabel(java.lang.String,
     *      java.util.Locale, java.lang.Object[])
     */
    @Override
    public String translateLabel(final String pKey, final Locale pLocale, final Object... pParams) {
        return translateText(null, pKey, pLocale, pParams);
    }

    /**
     * {@inheritDoc}
     * 
     * @see nemos.util.i18n.ITranslator#translateText(java.lang.String,
     *      java.lang.String, java.util.Locale, java.lang.Object[])
     */
    @Override
    public synchronized String translateText(final String pBaseName, final String pKey,
            final Locale pLocale, final Object... pParams) {

        final Bundle lBundle = mContext.getUsingBundle();

        // Ensure parameters are not null
        if (pKey == null) {
            throw new NullPointerException();
        }
        String lBaseName = pBaseName;
        if (lBaseName == null) {
            lBaseName = lBundle.getSymbolicName();
        }
        Locale lLocale = pLocale;
        if (lLocale == null) {
            lLocale = Locale.getDefault();
        }

        // Try the resources manager first
        String lLabel = null;
        if (mResourcesManager != null) {
            try {
                final IResources<String> lResources = mResourcesManager.getResources(lBaseName,
                        String.class, lLocale);
                if (lResources != null) {
                    lLabel = lResources.getResource(pKey);
                }
            } catch (final UnsupportedResourceType e) {
                mLogger.error(INVALID_TYPE_KEY, e, e.getMessage());
            } catch (final MissingResourceException e) {
                // Ignore
            }
        }

        // Then the l10n bundle file
        if (lLabel == null) {
            lLabel = mLocalization.getValue(pKey);
        }

        // Not found : return the key
        if (lLabel == null) {
            mLogger.warn(MISSING_KEY, pKey);
            lLabel = pKey;
        }
        // Found : format if needed
        else if (pParams != null && pParams.length > 0) {
            try {
                lLabel = String.format(lLocale, lLabel, pParams);
            } catch (final IllegalFormatException e) {
                mLogger.warn(INVALID_FORMAT_KEY, e, lLabel);
            }
        }

        return lLabel;
    }

    /**
     * Bind the resources manager.
     * 
     * @param pManager
     *            The resources manager
     */
    protected void bindResources(final IResourcesManager pManager) {
        mResourcesManager = pManager;
    }

    /**
     * Unind the resources manager.
     * 
     * @param pManager
     *            The resources manager
     */
    protected void unbindResources(@SuppressWarnings("unused") final IResourcesManager pManager) {
        mResourcesManager = null;
    }
}
